package io.potato.ts.service;

import io.potato.core.AppException;
import io.potato.core.CrudService;
import io.potato.ts.domain.Organ;
import io.potato.ts.repository.OrganRepository;
import io.potato.ts.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.ExampleMatcher.GenericPropertyMatchers;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


/**
 * 服务类
 * 
 * @author timl
 *
 * <p>2019-01-07 15:13:58</p>
 */
@Service
@Transactional
public class OrganService extends CrudService<Organ, Integer> {

	@Autowired
	OrganRepository repository;

	@Autowired
	UserRepository userRepository;

	@Override
	protected JpaRepository<Organ, Integer> getRepository() {
		return repository;
	}
	
	/**
	 * 根据名称查找单位（模糊匹配）
	 * @param pageable  分页排序信息
	 * @param name  单位名称
	 * @return  单位列表分页
	 */
	public Page<Organ> findByName(Pageable pageable, String name) {
		ExampleMatcher exampleMatcher = ExampleMatcher.matching()
				.withMatcher("name", GenericPropertyMatchers.contains());
		
		Organ obj = new Organ();
		obj.setName(name);
		
		return repository.findAll(Example.of(obj, exampleMatcher), pageable);
		
	}

	public void deleteById(Integer id) {

	    Long userCount = userRepository.countByOrganId(id);
	    if (userCount > 0) {
            throw new AppException("单位有关联的用户，不能删除");
        }

        this.getRepository().deleteById(id);
    }
	
}
